import { useState } from 'react';
import { redeemProductCode } from '../services/pocketBaseService';
import { useAuth } from '../contexts/AuthContext';

function RedeemCode() {
  const [code, setCode] = useState('');
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState(null);
  const [error, setError] = useState('');
  const { user } = useAuth();

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError('');
    setResult(null);

    if (!code.trim()) {
      setError('请输入核销码');
      setLoading(false);
      return;
    }

    const storeId = user && user.store ? user.store.id : undefined;
    if (!storeId) {
      setError('当前账号未绑定门店，无法核销');
      setLoading(false);
      return;
    }

    try {
      const response = await redeemProductCode(code.trim(), storeId);
      if (response.success) {
        setResult(response.data);
      } else {
        setError(response.error || '核销失败，请检查核销码是否正确');
      }
    } catch (err) {
      console.error('核销码兑换错误:', err);
      setError('处理请求时发生错误，请稍后再试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="container mx-auto px-4 py-8">
      <h2 className="text-2xl font-bold mb-6">核销码兑换</h2>

      <div className="bg-white shadow rounded-lg p-6 max-w-lg mx-auto">
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              核销码 <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              value={code}
              onChange={(e) => setCode(e.target.value)}
              placeholder="请输入核销码"
              className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
              required
            />
          </div>

          {error && (
            <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
              {error}
            </div>
          )}

          {result && (
            <div className="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded">
              <p className="font-bold">核销结果：</p>
              <p>{result.msg || '核销成功'}</p>
            </div>
          )}

          <div className="pt-2">
            <button
              type="submit"
              disabled={loading}
              className={`w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white ${
                loading ? 'bg-indigo-400' : 'bg-indigo-600 hover:bg-indigo-700'
              } focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500`}
            >
              {loading ? '处理中...' : '兑换商品'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

export default RedeemCode;